#include "Line.h"
#include "Csv.h"

bool
Line::initFromString(const QString &s)
{
   QStringList params;
   Csv csv;
   if(!csv.parse(s.toAscii().data(), params)) return false;

   bool ok;
   // The type
   if(params.size() > 1 && params.at(0).length() > 0)
   {
      type_ = stringToType(params.at(0));
   }

   // The flags
   if(params.size() > 2 && params.at(1).length() > 0)
   {
      int f;
      const QString &s = params.at(1);
      if(s.startsWith("0x", Qt::CaseInsensitive))
      {
         f = s.mid(2).toInt(&ok, 16);
      }
      else
      {
         f = s.toInt(&ok, 10);
      }

      if(!ok) return false;

      flags = Flags(Line::All) & f;
   }

   // The color
   if(params.size() > 3 && params.at(2).length() > 0)
   {
      setColor(stringToColor(params.at(2)));
   }

   // The color for up candles
   if(params.size() > 4 && params.at(3).length() > 0)
   {
      setUpColor(stringToColor(params.at(3)));
   }

   // The color for down candles
   if(params.size() > 5 && params.at(4).length() > 0)
   {
      setDownColor(stringToColor(params.at(4)));
   }

   if(params.size() > 6)
   {
      setLabel(params.at(5));
   }

   return true;
}

const QColor &
Line::stringToColor(const QString &s)
{
   if(s.length() < 6) return QColor::fromRgb(0, 0, 0);

   bool ok;
   int r = s.left(2).toInt(&ok, 16);
   if(!ok) return QColor::fromRgb(0, 0, 0);

   int g = s.mid(2, 2).toInt(&ok, 16);
   if(!ok) return QColor::fromRgb(0, 0, 0);

   int b = s.mid(4, 2).toInt(&ok, 16);
   if(!ok) return QColor::fromRgb(0, 0, 0);

   int a = 255;
   if(s.length() > 8)
   {
      a = s.mid(6, 2).toInt(&ok, 16);
      if(!ok) return QColor::fromRgb(0, 0, 0);
   }

   return QColor::fromRgb(r, g, b, a);
}